package net.sunniwell.weather;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.google.gson.Gson;

import android.text.TextUtils;

public class Weather {

	private static final String DEFAULT_APPCODE = "f4aed5cd98294efbb1169acb11a4bbcf";
	private static final String DEFAULT_CITYID = "2";
	private static final String DEFAULT_LATITUDE = "39.91488908";
	private static final String DEFAULT_LONGITUDE = "116.40387397";

	/**
	 * 
	 * 获取天气信息的json字符串 异步请求，请在子线程中加载
	 * 
	 * @param cityId
	 *            城市id
	 * @return json数据
	 */
	public static String getWeatherJson(String cityId) {
		return getWeatherJson(cityId, DEFAULT_APPCODE);
	}

	/**
	 * 
	 * 获取天气信息的json字符串 异步请求，请在子线程中加载
	 * 
	 * @param cityId
	 *            城市id
	 * @param appcode
	 *            墨迹天气个人申请的appcode
	 * @return json数据
	 */
	public static String getWeatherJson(String cityId, String appcode) {
		String host = "http://freecityid.market.alicloudapi.com";
		String path = "/whapi/json/alicityweather/briefcondition";
		String method = "POST";
		String weather = "查询失败";
		if (TextUtils.isEmpty(cityId)) {
			cityId = DEFAULT_CITYID;
		}
		if (TextUtils.isEmpty(appcode)) {
			cityId = DEFAULT_APPCODE;
		}
		Map<String, String> headers = new HashMap<String, String>();
		// 最后在header中的格式(中间是英文空格)为Authorization:APPCODE
		// 83359fd73fe94948385f570e3c139105
		headers.put("Authorization", "APPCODE " + appcode);
		// 根据API的要求，定义相对应的Content-Type
		headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
		Map<String, String> querys = new HashMap<String, String>();
		Map<String, String> bodys = new HashMap<String, String>();
		bodys.put("cityId", cityId);
		bodys.put("token", "46e13b7aab9bb77ee3358c3b672a2ae4");

		try {
			/**
			 * 重要提示如下: HttpUtils请从
			 * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/
			 * src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java 下载
			 *
			 * 相应的依赖请参照
			 * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/
			 * pom.xml
			 */
			HttpResponse response = doPost(host, path, method, headers, querys, bodys);
			// 获取response的body
			weather = EntityUtils.toString(response.getEntity());
			System.out.println(weather);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return weather;
	}

	/**
	 * 
	 * 获取天气信息的WeatherBean实体类 异步请求，请在子线程中加载
	 * 
	 * @param cityId
	 *            城市id
	 * @return
	 */
	public static WeatherBean getWeatherBean(String cityId) {
		return getWeatherBean(cityId, DEFAULT_APPCODE);
	}

	/**
	 * 
	 * 获取天气信息的WeatherBean实体类 异步请求，请在子线程中加载
	 * 
	 * @param cityId
	 *            城市id
	 * @param appcode
	 *            墨迹天气个人申请的appcode
	 * @return
	 */
	public static WeatherBean getWeatherBean(String cityId, String appcode) {
		if (TextUtils.isEmpty(cityId)) {
			cityId = DEFAULT_CITYID;
		}
		if (TextUtils.isEmpty(appcode)) {
			cityId = DEFAULT_APPCODE;
		}
		Gson gson = new Gson();
		WeatherBean weatherBean = null;
		String weather = getWeatherJson(cityId, appcode);
		if (!TextUtils.isEmpty(weather)) {
			weatherBean = gson.fromJson(weather, WeatherBean.class);
		}
		return weatherBean;
	}

	/**
	 * 
	 * 获取天气信息的json字符串 异步请求，请在子线程中加载
	 * 
	 * @param latitude
	 *            纬度
	 * @param longitude
	 *            经度
	 * @param appcode
	 *            墨迹天气个人申请的appcode
	 * @return json数据
	 */
	public static String getWeatherJson(String latitude, String longitude, String appcode) {
		String host = "http://apifreelat.market.alicloudapi.com";
		String path = "/whapi/json/aliweather/briefcondition";
		String method = "POST";
		String weather = "查询失败";
		if (TextUtils.isEmpty(latitude)) {
			latitude = DEFAULT_LATITUDE;
		}
		if (TextUtils.isEmpty(longitude)) {
			longitude = DEFAULT_LONGITUDE;
		}
		if (TextUtils.isEmpty(appcode)) {
			appcode = DEFAULT_APPCODE;
		}
		Map<String, String> headers = new HashMap<String, String>();
		// 最后在header中的格式(中间是英文空格)为Authorization:APPCODE
		// 83359fd73fe94948385f570e3c139105
		headers.put("Authorization", "APPCODE " + appcode);
		// 根据API的要求，定义相对应的Content-Type
		headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
		Map<String, String> querys = new HashMap<String, String>();
		Map<String, String> bodys = new HashMap<String, String>();
		bodys.put("lat", latitude);
		bodys.put("lon", longitude);
		bodys.put("token", "a231972c3e7ba6b33d8ec71fd4774f5e");

		try {
			/**
			 * 重要提示如下: HttpUtils请从
			 * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/
			 * src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java 下载
			 *
			 * 相应的依赖请参照
			 * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/
			 * pom.xml
			 */
			HttpResponse response = doPost(host, path, method, headers, querys, bodys);
			// 获取response的body
			weather = EntityUtils.toString(response.getEntity());
			System.out.println(weather);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return weather;
	}
	
	/**
	 * 
	 * 获取天气信息的WeatherBean实体类 异步请求，请在子线程中加载
	 * 
	 * @param latitude
	 *            纬度
	 * @param longitude
	 *            经度
	 * @param appcode
	 *            墨迹天气个人申请的appcode
	 * @return
	 */
	public static WeatherBean getWeatherBean(String latitude, String longitude, String appcode) {
		if (TextUtils.isEmpty(latitude)) {
			latitude = DEFAULT_LATITUDE;
		}
		if (TextUtils.isEmpty(longitude)) {
			longitude = DEFAULT_LONGITUDE;
		}
		if (TextUtils.isEmpty(appcode)) {
			appcode = DEFAULT_APPCODE;
		}
		Gson gson = new Gson();
		WeatherBean weatherBean = null;
		String weather = getWeatherJson(latitude, longitude, appcode);
		if (!TextUtils.isEmpty(weather)) {
			weatherBean = gson.fromJson(weather, WeatherBean.class);
		}
		return weatherBean;
	}

	/**
	 * post form
	 * 
	 * @param host
	 * @param path
	 * @param method
	 * @param headers
	 * @param querys
	 * @param bodys
	 * @return
	 * @throws Exception
	 */
	private static HttpResponse doPost(String host, String path, String method, Map<String, String> headers, Map<String, String> querys, Map<String, String> bodys) throws Exception {
		HttpClient httpClient = new DefaultHttpClient();

		HttpPost request = new HttpPost(buildUrl(host, path, querys));
		for (Map.Entry<String, String> e : headers.entrySet()) {
			request.addHeader(e.getKey(), e.getValue());
		}

		if (bodys != null) {
			List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();

			for (String key : bodys.keySet()) {
				nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
			}
			UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
			formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
			request.setEntity(formEntity);
		}

		return httpClient.execute(request);
	}

	private static String buildUrl(String host, String path, Map<String, String> querys) throws UnsupportedEncodingException {
		StringBuilder sbUrl = new StringBuilder();
		sbUrl.append(host);
		if (!TextUtils.isEmpty(path)) {
			sbUrl.append(path);
		}
		if (null != querys) {
			StringBuilder sbQuery = new StringBuilder();
			for (Map.Entry<String, String> query : querys.entrySet()) {
				if (0 < sbQuery.length()) {
					sbQuery.append("&");
				}
				if (TextUtils.isEmpty(query.getKey()) && !TextUtils.isEmpty(query.getValue())) {
					sbQuery.append(query.getValue());
				}
				if (!TextUtils.isEmpty(query.getKey())) {
					sbQuery.append(query.getKey());
					if (!TextUtils.isEmpty(query.getValue())) {
						sbQuery.append("=");
						sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
					}
				}
			}
			if (0 < sbQuery.length()) {
				sbUrl.append("?").append(sbQuery);
			}
		}

		return sbUrl.toString();
	}
}
